//
//  RProjectionScreenControlView.m
//  iPlan
//
//  Created by 侯伟 on 2021/9/29.
//

#import "RProjectionScreenControlView.h"
#import <Masonry/Masonry.h>
#import <SJVideoPlayer/SJProgressSlider.h>
#import <SJUIKit/NSAttributedString+SJMake.h>
#import <SJVideoPlayer/SJVideoPlayerControlMaskView.h>
#import <SJVideoPlayer/SJEdgeControlLayerAdapters.h>
#import <SJVideoPlayer/UIView+SJAnimationAdded.h>
#import <SJVideoPlayer/SJVideoPlayerConfigurations.h>


#import "CLUPnPServer.h"
#import "CLUPnP.h"

@interface RProjectionScreenControlView()<SJProgressSliderDelegate,CLUPnPResponseDelegate>{
    BOOL _isPlaying;
    NSInteger _volume;
    dispatch_source_t _timer;
    dispatch_queue_t _timeQueue;
}

@property (nonatomic, strong)CLUPnPRenderer *render;         //MDR渲染器

@property (nonatomic, strong)MyRelativeLayout *contentLayout;

@property (nonatomic, strong)MyRelativeLayout* topLayout;
@property (nonatomic, strong)UIButton *backBtn;
@property (nonatomic, strong)UILabel* deviceLb;
@property (nonatomic, strong)UILabel* titleLb;

@property (nonatomic, strong)UILabel* statusLb;

@property (nonatomic, strong)MyLinearLayout* midLayout;
@property (nonatomic, strong)UIButton *stopBtn;
@property (nonatomic, strong)UIButton *deviceBtn;

@property (nonatomic, strong)MyLinearLayout* bottomLayout;
@property (nonatomic, strong)UIButton *playBtn;
@property (nonatomic, strong)UILabel* currentTimeLb;
@property (nonatomic, strong)SJProgressSlider* slider;
@property (nonatomic, strong)UILabel* durationTimeLb;


@end

@implementation RProjectionScreenControlView
@synthesize restarted = _restarted;
- (void)dealloc{
    if(_timer){
        dispatch_source_cancel(_timer);
    }
    if(_device){
        _device = NULL;
    }
    
    if(_render){
        [_render stop];
        _render = NULL;
    }
}

- (instancetype)initWithFrame:(CGRect)frame{
    if(self = [super initWithFrame:frame]){
        self.backgroundColor =  HEXCOLOR(0x333333);
        _render = [CLUPnPRenderer new];
        _render.delegate = self;
        
        [self setupTimer];
        
        [self setupView];
    }
    return self;
}

- (void)setDevice:(CLUPnPDevice *)device{
    _device = device;
    _render.model = device;
    
    _deviceLb.text = device.friendlyName;
    [_deviceLb sizeToFit];
}

- (void)setUrl:(NSString *)url{
    _url = url;
    [_render setAVTransportURL:url];
    
    [Queue asyncMain:^{
        self.statusLb.textColor = COLOR_ORANGE;
        self.statusLb.text = @"连接中...";
        [self.statusLb sizeToFit];
    }];
}

- (void)setTitle:(NSString *)title{
    _title = title;
    _titleLb.text = title;
    [_titleLb sizeToFit];
}

- (void)setDuration:(NSTimeInterval)duration{
    _duration = duration;
    _durationTimeLb.text = [self stringWithTime:duration];
    [_durationTimeLb sizeToFit];
}

- (void)setupTimer {
    
    if(_timer) return;
    
    _timeQueue = dispatch_queue_create("com.cqys.timerQueue", DISPATCH_QUEUE_CONCURRENT);
    _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, _timeQueue);
    dispatch_source_set_timer(_timer, DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC, 0);
    dispatch_source_set_event_handler(_timer, ^{
        [self.render getPositionInfo];
    });
}


#pragma mark -- SJControlLayer
///
/// 控制层入场
///     当播放器将要切换到此控制层时, 该方法将会被调用
///     可以在这里做入场的操作
///
- (void)restartControlLayer {
    _restarted = YES;
    sj_view_makeAppear(self, YES);
    sj_view_makeAppear(self.contentLayout, YES);
}


///
/// 退出控制层
///     当播放器将要切换到其他控制层时, 该方法将会被调用
///     可以在这里处理退出控制层的操作
///
- (void)exitControlLayer {
    _restarted = NO;
    
    sj_view_makeDisappear(self.contentLayout, YES);
    sj_view_makeDisappear(self, YES, ^{
        if (!self->_restarted) [self removeFromSuperview];
    });
    
    if(_timer){
        dispatch_suspend(_timer);
    }
    [self.render stop];
}

///
/// 控制层视图
///     当切换为当前控制层时, 该视图将会被添加到播放器中
///
- (UIView*)controlView {
    return self;
}


#pragma mark - item actions

//返回
- (void)backItemWasTapped:(UIButton*)sender{
    //停止
    [self.render stop];
    _render = NULL;
    _device = NULL;
    
    if ( [self.delegate respondsToSelector:@selector(backItemClickOnTheControlLayer:)] ) {
        [self.delegate backItemClickOnTheControlLayer:self];
    }
}

//停止投屏
- (void)stopItemWasTapped:(UIButton*)sender{
    [self.render stop];
    if ( [self.delegate respondsToSelector:@selector(stopItemClickOnTheControlLayer:)] ) {
        [self.delegate stopItemClickOnTheControlLayer:self];
    }
}

///切换
- (void)switchWasTapped:(UIButton*)sender{
    if ([self.delegate respondsToSelector:@selector(switchItemClickOnTheControlLayer:)] ) {
        [self.delegate switchItemClickOnTheControlLayer:self];
    }
}

- (void)playItemTapedd:(UIButton*)sender{
    if (_isPlaying) {
        [self.render pause];
    }else{
        [self.render play];
    }
}

- (void)volumeAdd:(UIButton*)sender{
    if(_volume < 100){
        _volume++;
        [self.render setVolumeWith:[NSString stringWithFormat:@"%ld",_volume]];
    }
}

- (void)volumeReduce:(UIButton*)sender{
    if(_volume > 0){
        _volume--;
        [self.render setVolumeWith:[NSString stringWithFormat:@"%ld",_volume]];
    }
}



#pragma mark  -- SJProgressSliderDelegate

- (void)sliderWillBeginDragging:(SJProgressSlider *)slider{
    if(self->_timer){
        dispatch_suspend(self->_timer);
    }
}

- (void)sliderDidEndDragging:(SJProgressSlider *)slider{
    
    NSInteger relTime = self.duration*slider.value;
    
    [self.render seek:relTime];
    
    if(self->_timer){
        dispatch_resume(self->_timer);
    }
}


// 响应解析回调协议
#pragma mark -- CLUPnPResponseDelegate
/**
 未定义的响应/错误
 
 @param resXML  响应XML
 @param postXML 请求的动作
 */
- (void)upnpUndefinedResponse:(NSString *)resXML postXML:(NSString *)postXML{
    
//    if ([postXML hasSuffix:@"SetAVTransportURIResponse"]) {
//
//    }else if ([postXML hasSuffix:@"SetNextAVTransportURIResponse"]){
//
//    }else if ([postXML hasSuffix:@"PauseResponse"]){
//
//    }else if ([postXML hasSuffix:@"PlayResponse"]){
//
//    }else if ([postXML hasSuffix:@"StopResponse"]){
//
//    }else if ([postXML hasSuffix:@"SeekResponse"]){
//
//    }else if ([postXML hasSuffix:@"NextResponse"]){
//
//    }else if ([postXML hasSuffix:@"PreviousResponse"]){
//
//    }else if ([postXML hasSuffix:@"SetVolumeResponse"]){
//
//    }else if ([postXML hasSuffix:@"GetVolumeResponse"]){
//
//    }else if ([postXML hasSuffix:@"GetPositionInfoResponse"]){
//
//    }else if ([postXML hasSuffix:@"GetTransportInfoResponse"]){
//
//    }
}

// 设置url响应
- (void)upnpSetAVTransportURIResponse{
    [self.render play];
}

// 获取播放状态
- (void)upnpGetTransportInfoResponse:(CLUPnPTransportInfo *)info{
    if (!([info.currentTransportState isEqualToString:@"PLAYING"] || [info.currentTransportState isEqualToString:@"TRANSITIONING"])) {
        [self.render play];
        
        [Queue asyncMain:^{
            self.statusLb.textColor = COLOR_RED;
            self.statusLb.text = @"连接失败";
            [self.statusLb sizeToFit];
        }];
    }else{
        [Queue asyncMain:^{
            self.statusLb.textColor = COLOR_GREEN;
            self.statusLb.text = @"连接成功";
            [self.statusLb sizeToFit];
        }];
    }
}
// 播放响应
- (void)upnpPlayResponse{
    [Queue asyncMain:^{
        
        self->_isPlaying = YES;
        self.playBtn.selected = YES;
        
        if(self -> _timer){
            dispatch_resume(self -> _timer);
        }
        
        //获取时长
        [self.render getPositionInfo];
        
        //获取音量
        [self.render getVolume];
    }];
}

// 暂停响应
- (void)upnpPauseResponse{
    [Queue asyncMain:^{
        
        self->_isPlaying = NO;
        self.playBtn.selected = NO;
        
        if(self->_timer){
            dispatch_suspend(self->_timer);
        }
    }];
}
// 停止投屏
- (void)upnpStopResponse{
    [Queue asyncMain:^{
        
        self->_isPlaying = NO;
        self.playBtn.selected = NO;
        
        if(self->_timer){
            dispatch_suspend(self->_timer);
        }
    }];
}
// 跳转响应
- (void)upnpSeekResponse{
    
}
// 以前的响应
- (void)upnpPreviousResponse{
    
}
// 下一个响应
- (void)upnpNextResponse{
    
}
// 设置音量响应
- (void)upnpSetVolumeResponse{
    
}
// 设置下一个url响应
- (void)upnpSetNextAVTransportURIResponse{
    
}

// 获取音频信息
- (void)upnpGetVolumeResponse:(NSString *)volume{
    _volume = [volume integerValue];
}


// 获取播放进度
- (void)upnpGetPositionInfoResponse:(CLUPnPAVPositionInfo *)info{
    
    [Queue asyncMain:^{
        //当前时间
        self.currentTimeLb.text = [self stringWithTime:info.relTime];
        [self.currentTimeLb sizeToFit];
        
        //总时长
        if(info.trackDuration > 0){
            self.durationTimeLb.text = [self stringWithTime:info.trackDuration];
            [self.durationTimeLb sizeToFit];
        }
        
        //进度
        if(info.trackDuration > 0){
            [self.slider setValue:info.relTime/info.trackDuration animated:YES];
        }else if(self.duration > 0){
            [self.slider setValue:info.relTime/self.duration animated:YES];
        }
    }];
}


#pragma mark -- setupView

- (void)setupView {
    
    MyRelativeLayout* contentLayout = [MyRelativeLayout new];
    contentLayout.myMargin = 0;
    [self addSubview:contentLayout];
    _contentLayout = contentLayout;
    
    
    MyRelativeLayout* topLayout = [MyRelativeLayout new];
    topLayout.myTop = 0;
    topLayout.myHeight = 40;
    topLayout.myHorzMargin = 0;
    [contentLayout addSubview:topLayout];
    
    UIButton* backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [backBtn setImage:[UIImage imageNamed:@"common_back_white"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(backItemWasTapped:) forControlEvents:UIControlEventTouchUpInside];
    backBtn.mySize = CGSizeMake(40, 40);
    backBtn.myLeft = backBtn.myCenterY = 0;
    [backBtn sizeToFit];
    [topLayout addSubview:backBtn];
    _backBtn = backBtn;

    UILabel* titleLb = [UILabel lableWithFont:FONT(14) color:UIColor.whiteColor text:@""];
    titleLb.leftPos.equalTo(backBtn.rightPos).offset(0);
    titleLb.myCenterY = 0;
    [topLayout addSubview:titleLb];
    _titleLb = titleLb;
    
    UILabel* deviceLb = [UILabel lableWithFont:FONT(16) color:COLOR_ORANGE text:@""];
    deviceLb.myCenterX = 0;
    deviceLb.myCenterY = 0;
    [topLayout addSubview:deviceLb];
    _deviceLb = deviceLb;
    
    UILabel* statusLb = [UILabel lableWithFont:FONT(13) color:COLOR_ORANGE text:@"连接中..."];
    statusLb.textAlignment = NSTextAlignmentCenter;
    statusLb.myCenterX = 0;
    statusLb.topPos.equalTo(topLayout.bottomPos).offset(8.0);
    [contentLayout addSubview:statusLb];
    _statusLb = statusLb;
    
    
    MyLinearLayout* midLayout = [MyLinearLayout linearLayoutWithOrientation:(MyOrientation_Horz)];
    midLayout.myHeight = 40;
    midLayout.myCenterY = 0;
    midLayout.myHorzMargin = 40;
    midLayout.gravity = MyGravity_Horz_Center;
    midLayout.subviewHSpace = 32;
    midLayout.padding = UIEdgeInsetsMake(0, 16, 0, 16);
    [contentLayout addSubview:midLayout];
    
    
    UIButton* stopBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    stopBtn.backgroundColor = RGBACOLOR(0xFF, 0xFF, 0xFF, 0.3);
    [stopBtn setTitleColor:COLOR_WHITE forState:UIControlStateNormal];
    [stopBtn setTitle:@"退出投屏" forState:UIControlStateNormal];
    [stopBtn addTarget:self action:@selector(stopItemWasTapped:) forControlEvents:UIControlEventTouchUpInside];
    stopBtn.titleLabel.font = FONT_FIT(14);
    stopBtn.mySize = CGSizeMake(PX(80), PX(32));
    stopBtn.myCenterY = 0;
    stopBtn.layer.cornerRadius = PX(16);
    [midLayout addSubview:stopBtn];
    _stopBtn = stopBtn;
    
    UIButton* deviceBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    deviceBtn.backgroundColor = RGBACOLOR(0xFF, 0xFF, 0xFF, 0.3);
    [deviceBtn setTitleColor:COLOR_WHITE forState:UIControlStateNormal];
    [deviceBtn setTitle:@"切换设备" forState:UIControlStateNormal];
    [deviceBtn addTarget:self action:@selector(switchWasTapped:) forControlEvents:UIControlEventTouchUpInside];
    deviceBtn.titleLabel.font = FONT_FIT(14);
    deviceBtn.mySize = CGSizeMake(PX(80), PX(32));
    deviceBtn.myCenterY = 0;
    deviceBtn.layer.cornerRadius = PX(16);
    [midLayout addSubview:deviceBtn];
    _deviceBtn = deviceBtn;
    
    
    MyLinearLayout* bottomLayout = [MyLinearLayout linearLayoutWithOrientation:(MyOrientation_Horz)];
    bottomLayout.myHeight = 40;
    bottomLayout.myBottom = 0;
    bottomLayout.myHorzMargin = 0;
    bottomLayout.subviewHSpace = 16;
    bottomLayout.padding = UIEdgeInsetsMake(0, 16, 0, 16);
    [contentLayout addSubview:bottomLayout];
    
    UIButton* playBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [playBtn setImage:SJVideoPlayerConfigurations.shared.resources.playImage forState:UIControlStateNormal];
    [playBtn setImage:SJVideoPlayerConfigurations.shared.resources.pauseImage forState:UIControlStateSelected];
    [playBtn addTarget:self action:@selector(playItemTapedd:) forControlEvents:UIControlEventTouchUpInside];
    playBtn.mySize = CGSizeMake(PX(32), PX(32));
    playBtn.myCenterY = 0;
    [bottomLayout addSubview:playBtn];
    _playBtn = playBtn;
    
    
    UILabel* currentTimeLb = [UILabel lableWithFont:FONT(14) color:UIColor.whiteColor text:@"00:00:00"];
    currentTimeLb.textAlignment = NSTextAlignmentCenter;
    currentTimeLb.myLeft = 0;
    currentTimeLb.myCenterY = 0;
    [bottomLayout addSubview:currentTimeLb];
    _currentTimeLb = currentTimeLb;
    
    SJProgressSlider* slider = [SJProgressSlider new];
    slider.delegate = self;
    [slider setThumbCornerRadius:8 size:CGSizeMake(16, 16) thumbBackgroundColor:COLOR_WHITE];
    slider.trackHeight = 4.0;
    slider.myCenterY = 0;
    slider.weight = 1.0;
    slider.myHeight = 16;
    [bottomLayout addSubview:slider];
    _slider = slider;
    
    UILabel* totalTimeLb = [UILabel lableWithFont:FONT(14) color:UIColor.whiteColor text:@"00:00:00"];
    totalTimeLb.textAlignment = NSTextAlignmentCenter;
    totalTimeLb.myRight = 0;
    totalTimeLb.myCenterY = 0;
    [bottomLayout addSubview:totalTimeLb];
    _durationTimeLb = totalTimeLb;
    
    
    MyRelativeLayout* rightLayout = [MyRelativeLayout new];
    rightLayout.backgroundColor = UIColor.blackColor;
    rightLayout.layer.cornerRadius = 4;
    rightLayout.myWidth = 32;
    rightLayout.topPos.equalTo(topLayout.bottomPos).offset(0);
    rightLayout.bottomPos.equalTo(bottomLayout.topPos).offset(0);
    rightLayout.myRight = 16;
    [contentLayout addSubview:rightLayout];
    
    UIButton* addBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [addBtn addTarget:self action:@selector(volumeAdd:) forControlEvents:UIControlEventTouchUpInside];
    [addBtn setTitle:@"+" forState:UIControlStateNormal];
    addBtn.titleLabel.font = FONTBOLD(20);
    addBtn.mySize = CGSizeMake(32, 32);
    addBtn.myTop = 0;
    [rightLayout addSubview:addBtn];
    [addBtn sizeToFit];
    
    UILabel* xLb = [UILabel lableWithFont:FONT(14) color:UIColor.whiteColor text:@"音\n量"];
    xLb.myHeight = MyLayoutSize.wrap;
    xLb.textAlignment = NSTextAlignmentCenter;
    xLb.myCenterY = 0;
    xLb.myHorzMargin = 0;
    [rightLayout addSubview:xLb];
    
    UIButton* reduceBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [reduceBtn addTarget:self action:@selector(volumeReduce:) forControlEvents:UIControlEventTouchUpInside];
    [reduceBtn setTitle:@"-" forState:UIControlStateNormal];
    reduceBtn.titleLabel.font = FONTBOLD(20);
    reduceBtn.mySize = CGSizeMake(32, 32);
    reduceBtn.myBottom = 0;
    [rightLayout addSubview:reduceBtn];
    [reduceBtn sizeToFit];
}


- (NSString*)stringWithTime:(long)time {
    long min = 60;
    long hour = 60 * min;
    
    if (time < hour) {
        return [NSString stringWithFormat:@"%02ld:%02ld", time/min, time%min];
    }else{
        return [NSString stringWithFormat:@"%ld:%02ld:%02ld", time/hour, time%hour/min, time%min];
    }
}
@end
